package com.orientation.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.orientation.commom.exception.CustomException;
import com.orientation.service.UserService;
import com.orientation.vo.FileVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Api(tags = "文件操作")
@Validated
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {
    @Value("${file.upload-path}")
    private String uploadPath;
    @Resource
    private UserService userService;

    /**
     * 单文件上传
     *
     * @param file
     * @return
     */
    @ApiOperation("单文件上传 无用")
    @PostMapping("/upload")
    public FileVo upload(MultipartFile file) {

        FileVo fileVO = new FileVo();
        String flag = System.currentTimeMillis() + "";
        fileVO.setFlag(flag);
        String fileName = file.getOriginalFilename();
        fileVO.setFileName(fileName);
        System.out.println(uploadPath);
        try {
            FileUtil.writeBytes(file.getBytes(), uploadPath + flag + "-" + fileName);
            System.out.println(fileName + "--上传成功");
            Thread.sleep(1L);
        } catch (Exception e) {
            System.err.println(fileName + "--文件上传失败");
        }
        return fileVO;
    }

    /**
     * 多文件上传
     *
     * @param request
     * @return
     */
    @ApiOperation("多文件上传 无用")
    @PostMapping("/upload/multiple")
    public List<FileVo> multipleUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("files");
        List<FileVo> fileVos = Lists.newArrayList();
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                continue;
            }
            String flag = System.currentTimeMillis() + "";
            String fileName = file.getOriginalFilename();
            FileVo fileVO = new FileVo();
            fileVO.setFlag(flag);
            fileVO.setFileName(file.getOriginalFilename());
            fileVos.add(fileVO);
            try {
                FileUtil.writeBytes(file.getBytes(), uploadPath + flag + "-" + fileName);
                System.out.println(fileName + "--上传成功");
                Thread.sleep(1L);
            } catch (Exception e) {
                System.err.println(fileName + "--文件上传失败");
            }

        }
        return fileVos;
    }

    /**
     * 获取文件
     *
     * @param flag
     * @param response
     */
    @ApiOperation("下载文件无用")
    @GetMapping("/{flag}")
    public void avatarPath(@PathVariable String flag, HttpServletResponse response) {
        OutputStream os;
        List<String> fileNames = FileUtil.listFileNames(uploadPath);
        String avatar = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        try {
            if (StrUtil.isNotEmpty(avatar)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(avatar, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(uploadPath + avatar);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }

    /**
     * 获取模板
     *
     * @param response
     */
    @ApiOperation("模板下载")
    @GetMapping("/template")
    public void downTemp(HttpServletResponse response) throws IOException {
        org.springframework.core.io.ClassPathResource classPathResource = new ClassPathResource("static/template/newStudent.xlsx");
        OutputStream os;
        response.addHeader("Content-Disposition", "attachment;filename=student.xlsx");
        response.setContentType("application/octet-stream");
        byte[] bytes = FileUtil.readBytes(classPathResource.getPath());
        os = response.getOutputStream();
        os.write(bytes);
        os.flush();
        os.close();
    }



    @ApiOperation("图片上传")
    @PostMapping("/uploadmaig")
    public void insertImage(MultipartFile file, @RequestParam String loginName, HttpServletRequest request) throws IOException {

        if (file == null) {
            throw new CustomException("18", "请选择新图片");
        }
        String end = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        //转换为小写
        String suffix = end.toLowerCase();
        System.out.println(end);
        if (!suffix.equals(".jpg") && !suffix.equals(".jpeg") && !suffix.equals(".png")/* || suffix.equals(".gif")*/) {
            throw new CustomException("18", "文件格式不对，请重新选择");
        }
        //文件名先产生一个uuid 在和真是文件名拼接起来，防止文件重复上传失败
        String fileName = UUID.randomUUID().toString() + file.getOriginalFilename();
       // 得到文件存取位置
        File savePathFile = new File(uploadPath);
        if (!savePathFile.exists()) {
            //若不存在该目录，则创建目录
            savePathFile.mkdir();
        }
        //保存
        try {
            //将文件保存指定目录
            file.transferTo(new File(uploadPath + fileName));
        } catch (Exception e) {
            log.error("保存文件异常{}", e);
            e.printStackTrace();
            throw new CustomException("18", "保存文件异常");

        }
        //项目url，这里可以使用常量或者去数据字典获取相应的url前缀；
        String fileUrl = "http://localhost:9998";
        //文件获取路径
        fileUrl = fileUrl + "/uploadfile/" + fileName;
        //入库操作
        userService.updateMy(loginName, null, null, null, fileUrl);
    }
   /* @PostMapping("/upload")
    public String upload(@RequestParam("file")MultipartFile[] files){
        System.out.println("文件长度："+files.length);

        File saveFile = new File(uploadPath);
        if (!saveFile.exists()) {
            //若不存在该目录，则创建目录
            saveFile.mkdir();
        }
//        存在文件
        if(files!=null & files.length>0){
            for(MultipartFile multipartFile : files){
                String fileName = multipartFile.getOriginalFilename();
                File file1 = new File(uploadPath);
                try{
                    //将接收到的前端文件上传到本地目录
                    multipartFile.transferTo(new File(uploadPath + fileName));
                }catch (IOException e){
                    e.printStackTrace();
                    return "上传失败";
                }
                System.out.println("");
            }
        }
        return "ok";
    }*/
    @ApiOperation("多文件传")
    @PostMapping("/insertImageFiles")
    public void insertImageFiles(MultipartFile[] file, @RequestParam String loginName, HttpServletRequest request) throws IOException {
/*   if(files!=null & files.length>0){
            for(MultipartFile multipartFile : files){
                String fileName = multipartFile.getOriginalFilename();
                File file1 = new File(uploadPath);
                try{
                    //将接收到的前端文件上传到本地目录
                    multipartFile.transferTo(new File(uploadPath + fileName));
                }catch (IOException e){
                    e.printStackTrace();
                    return "上传失败";
                }
                System.out.println("");
            }
        }*/
//        if (file == null) {
//            throw new CustomException("18", "请选择新图片");
//        }
//        String end = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
//        //转换为小写
//        String suffix = end.toLowerCase();
//        System.out.println(end);
//        if (!suffix.equals(".jpg") && !suffix.equals(".jpeg") && !suffix.equals(".png")/* || suffix.equals(".gif")*/) {
//            throw new CustomException("18", "文件格式不对，请重新选择");
//        }
//        //文件名先产生一个uuid 在和真是文件名拼接起来，防止文件重复上传失败
//        String fileName = UUID.randomUUID().toString() + file.getOriginalFilename();
//        // 得到文件存取位置
//        File savePathFile = new File(uploadPath);
//        if (!savePathFile.exists()) {
//            //若不存在该目录，则创建目录
//            savePathFile.mkdir();
//        }
//        //保存
//        try {
//            //将文件保存指定目录
//            file.transferTo(new File(uploadPath + fileName));
//        } catch (Exception e) {
//            log.error("保存文件异常{}", e);
//            e.printStackTrace();
//            throw new CustomException("18", "保存文件异常");
//        }
//        //项目url，这里可以使用常量或者去数据字典获取相应的url前缀；
//        String fileUrl = "http://localhost:9998";
//        //文件获取路径
//        fileUrl = fileUrl + "/uploadfile/" + fileName;
//        //入库操作
//        userService.updateMy(loginName, null, null, null, fileUrl);
    }
}
